package com.chwn.curiousdiary.ui.search;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.adapter.HotSearchAdapter;
import com.chwn.curiousdiary.adapter.StoryListAdapter;
import com.chwn.curiousdiary.bean.HotSearchBean;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.bean.StoryListBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.service.AudioService;
import com.chwn.curiousdiary.ui.play.activity.StoryPlayActivity;
import com.chwn.curiousdiary.ui.story.activity.StoryTypeActivity;
import com.chwn.harulib.adapter.ViewHolder;
import com.chwn.harulib.adapter.interfaces.OnItemClickListener;
import com.chwn.harulib.mvp.base.BaseMVPFragment;
import com.chwn.harulib.util.KeyBoardUtils;
import com.chwn.harulib.util.StringUtil;
import com.chwn.harulib.widget.tag.FlowLayout;
import com.chwn.harulib.widget.tag.TagFlowLayout;
import com.chwn.harulib.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Myshikin on 2017/8/8.
 */

public class SearchFragment extends BaseMVPFragment<SearchPresenter> implements SearchContract.View,
        XRecyclerView.LoadingListener {
    private static final int HOT_TAG_VIEW      = 0;
    private static final int CONTENT_VIEW      = 1;
    private static final int LOADING_VIEW      = 2;
    private static final int LOADING_FIAL_VIEW = 3;

    @BindView(R.id.et_search)
    EditText      mSearchET;
    @BindView(R.id.iv_clear_input)
    ImageView     mClearInputIV;
    @BindView(R.id.rv_content)
    XRecyclerView mContentRV;

    @BindView(R.id.ll_loading)
    LinearLayout mLoadingView;
    @BindView(R.id.ll_load_empty)
    LinearLayout mEmptyView;
    @BindView(R.id.ll_hot_search)
    LinearLayout mHotSearchView;

    @BindView(R.id.tag_hot)
    TagFlowLayout mHotTag;

    private List<HotSearchBean> hotKeys;

    private int nowPage = 1;
    private String searchKey;
    private boolean isRefresh = true;

    private StoryListAdapter mStoryListAdapter;

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initContentView() {

        ButterKnife.bind(this, mInflateContentView);

        mLLContentView.setBackgroundColor(mActivity.getResources().getColor(R.color.search_gray));
        mContentRV.setLoadingMoreEnabled(true);
        mContentRV.setLoadingListener(this);
        mContentRV.setLayoutManager(new LinearLayoutManager(mActivity));
        mStoryListAdapter = new StoryListAdapter(mActivity, null, false);
        mContentRV.setAdapter(mStoryListAdapter);
        KeyBoardUtils.openKeybord(mSearchET , mActivity );
    }

    @Override
    protected void initListener() {
        super.initListener();
        mStoryListAdapter.setOnItemClickListener(new OnItemClickListener<StoryListBean>() {
            @Override
            public void onItemClick(ViewHolder viewHolder, StoryListBean data, int position) {
                onStoryListItemClick(data, position);
            }
        });

        mSearchET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString())) {
                    mClearInputIV.setVisibility(View.GONE);
                } else {
                    mClearInputIV.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mSearchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    clickSearch();
                    return false;
                }
                return false;
            }
        });
    }

    @Override
    protected void getData() {
        showContentView();
        showView(HOT_TAG_VIEW);
        mPresenter.getHotSearch();
    }

    @Override
    public void showHotSearch(final List<HotSearchBean> hotKeys) {
        this.hotKeys = hotKeys;
        mSearchET.setHint(hotKeys.get(0).getKey_name());
        HotSearchAdapter hotSearchAdapter = new HotSearchAdapter(hotKeys, mActivity);
        mHotTag.setAdapter(hotSearchAdapter);
        mHotTag.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                searchKey = hotKeys.get(position).getKey_name();
                searchStory(nowPage, searchKey);
                mSearchET.setText(searchKey);
                KeyBoardUtils.hideSoftInput(mSearchET);
                onRequestStart();
                return false;
            }
        });
    }

    @Override
    public void showSearchStories(List<StoryListBean> storyList) {
        if (isRefresh) {
            mStoryListAdapter.setNewData(storyList);
            mContentRV.refreshComplete();
        } else {
            mStoryListAdapter.setLoadMoreData(storyList);
            mContentRV.loadMoreComplete();
        }
        if (storyList.size() < Constant.PAGE_COUNT) {
            mContentRV.noMoreLoading();
        }
        showView(CONTENT_VIEW);
    }

    @OnClick({R.id.tv_search, R.id.ib_back, R.id.iv_clear_input})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                clickSearch();
                KeyBoardUtils.hideSoftInput(mSearchET);
                break;
            case R.id.ib_back:
                KeyBoardUtils.hideSoftInput(mSearchET);
                getActivity().finish();
                break;
            case R.id.iv_clear_input:
                mSearchET.setText("");
                break;
        }
    }

    private void onStoryListItemClick(StoryListBean data, int position) {
        if (data.getsParts() == 2) { //故事包
            enterStoryType(data);
        } else { //故事
            enterStoryPlay(position);
        }
    }

    /**
     * 进入故事集的列表界面
     * @param data
     */
    private void enterStoryType(StoryListBean data) {
        Intent intent = new Intent(getActivity(), StoryTypeActivity.class);
        intent.putExtra(Constant.JUMP_TYPE, data.getStoryPackageId());
        intent.putExtra(Constant.STORY_LIST, data.getStoryPackageTitle());
        startActivity(intent);
    }

    /**
     * 进入播放界面
     */
    private void enterStoryPlay(int position) {
        List<StoryListBean> datas = mStoryListAdapter.getDatas();

        ArrayList<StoryBean> storyList = new ArrayList<>();
        int mark = 0;
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).getsParts() == 1) {
                storyList.add(new StoryBean(datas.get(i)));
            } else if (datas.get(i).getsParts() == 2) {
                mark++;
            }
        }

        Intent intent = new Intent(getActivity(), StoryPlayActivity.class);
        intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.NEWEST_ENTER);
        intent.putExtra(Constant.PACKAGE_ID, StringUtil.getRandomString());
        intent.putExtra("list", storyList);
        intent.putExtra("position", position - mark);
        startActivity(intent);
    }

    private void clickSearch() {
        nowPage = 1;
        searchKey = TextUtils.isEmpty(mSearchET.getText().toString().trim()) ? mSearchET.getHint().toString().trim() : mSearchET.getText().toString().trim();
        mSearchET.setText(searchKey);
        onRequestStart();
        searchStory(nowPage, searchKey);
    }

    private void searchStory(int page, String searchKey) {
        if (!TextUtils.isEmpty(searchKey)) {
            mPresenter.getSearchStories(page, searchKey);
        }
    }

    @Override
    public void onRefresh() {
        nowPage = 1;
        isRefresh = true;
        searchStory(nowPage, searchKey);
    }

    @Override
    public void onLoadMore() {
        nowPage++;
        isRefresh = false;
        searchStory(nowPage, searchKey);
    }

    @Override
    public void onRequestStart() {
        showView(LOADING_VIEW);
    }

    @Override
    public void onRequestError(Throwable e) {
        super.onRequestError(e);
        mContentRV.loadMoreComplete();
        mContentRV.refreshComplete();

        if (isRefresh || mStoryListAdapter.getDatas() == null || mStoryListAdapter.getDatas().size() < 1) {
            showEmptyView();
        } else {
            mContentRV.noMoreLoading();
        }
    }

    @Override
    public void showEmptyView() {
        showView(LOADING_FIAL_VIEW);
    }

    private void showView(int tag) {
        mHotSearchView.setVisibility(tag == HOT_TAG_VIEW ? View.VISIBLE : View.GONE);
        mContentRV.setVisibility(tag == CONTENT_VIEW ? View.VISIBLE : View.GONE);
        mLoadingView.setVisibility(tag == LOADING_VIEW ? View.VISIBLE : View.GONE);
        mEmptyView.setVisibility(tag == LOADING_FIAL_VIEW ? View.VISIBLE : View.GONE);
    }
}
